package netTools;

import java.util.ArrayList;
import java.util.List;

/**
 * Used for file transfers. PortManager gives a thread a free port number which the latter
 * can wait for incoming connections. If all ports are busy thread will wait till one frees.
 * @author pasquale
 *
 */
public class PortManager {
	
	private int BASE_PORT; //default base port
	private int PORT_LEN; //default port length
	
	List<Integer> freePorts;
	
	public PortManager(int basePort,int portLength){
		freePorts = new ArrayList<Integer>();
		BASE_PORT = basePort;
		PORT_LEN = portLength;
		for (int i = 0; i< PORT_LEN;i++)
			freePorts.add((BASE_PORT+i));
	}
	
	public synchronized int getPortNumber(){
		while(freePorts.size() == 0) //wait until a port frees
			try {
				wait();
			} catch (InterruptedException e) {
			}
		
		return freePorts.remove(0); //returns first free port
	}
	
	public synchronized void freePort(int port){
		freePorts.add(port);
		this.notifyAll();
	}

}